/**
 * Copyright 2006 gworks.com.au
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. (http://www.apache.org/licenses/LICENSE-2.0)
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed 
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
 * the specific language governing permissions and limitations under the License.
 *
 * <dhamma-message src="Atisha (11th century Tibetan Buddhist master)">
 * 	The greatest achievement is selflessness. The greatest worth is self-mastery.
 * 	The greatest quality is seeking to serve others. The greatest precept is continual awareness.
 * 	The greatest medicine is the emptiness of everything. The greatest action is not conforming with the worlds ways.
 * 	The greatest magic is transmuting the passions. The greatest generosity is non-attachment.
 * 	The greatest goodness is a peaceful mind. The greatest patience is humility.
 * 	The greatest effort is not concerned with results. The greatest meditation is a mind that lets go.
 * 	The greatest wisdom is seeing through appearances. 
 * </dhamma-message>
 */
package au.com.gworks.jump.app.wiki.client.navigation;

import java.util.Map;

import org.javaongems.client.Gem;
import org.javaongems.client.forms.Form;
import org.javaongems.client.forms.FormController;
import org.javaongems.client.service.HttpPostRpc;
import org.javaongems.client.service.HttpPostRpcAsync;
import org.javaongems.client.service.HttpPostRpc.ProgressInfo;
import org.javaongems.client.stdctrls.BorderLayoutPanel;
import org.javaongems.client.stdctrls.DialogButtonPanel;
import org.javaongems.client.stdctrls.FieldsetLayoutPanel;
import org.javaongems.client.stdctrls.HttpPostForm;
import org.javaongems.client.stdctrls.Image;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class FileUpload  {
	static public class Dialog extends Form {
		private BorderLayoutPanel	container = new BorderLayoutPanel();
		private FieldsetLayoutPanel	layout = new FieldsetLayoutPanel();
		private DialogButtonPanel	buttonPanel = new DialogButtonPanel();
		
		private TextArea			commentMmo = new TextArea();
		private Button				okBtn		= new Button("OK");
		private Button				cancelBtn	= new Button("Cancel");
		private ScrollPanel			scroller = new ScrollPanel();
		private HttpPostForm		uploader	= new HttpPostForm();
		
		private Controller controller;
		
		public Dialog(Controller ctrlr) {
			super(ctrlr);
			controller = ctrlr;
			initialiseFormStyle();
			initialiseLayout();
			initialiseWidgets();
			setFormActionListener(controller);
			uploader.setProgressListener(controller);
		}
		
		private void initialiseFormStyle() {
			DOM.setAttribute(getElement(), "id", "jumpFileUploadDialog");
			setWidth("570px");
		}
		
		private void initialiseLayout() {
			add(container);
			layout.setTitle("Change information");
			container.setWidget(layout, BorderLayoutPanel.CENTER);
			container.setWidget(buttonPanel, BorderLayoutPanel.SOUTH);
			
			layout.addWidget("File(s)", scroller);
			layout.addWidget("Comment", commentMmo);
			buttonPanel.add(okBtn);
			buttonPanel.add(DialogButtonPanel.createSeparator());
			buttonPanel.add(cancelBtn);
			scroller.add(uploader);
			layout.render();
		}
		
		private void initialiseWidgets() {
			layout.setHeight("100%");
			uploader.setUrl(Gem.stone.getApplCtx() + "jsps/sample-upload-form.jsp?gemsBaseName=uploadFile&gemsMaxUploads=20");
			String uri = HttpPostRpc.Utils.prepareEndpoint(uploader.getOrderNo());
			uploader.setAction(uri);
			scroller.setWidth("100%");
			uploader.setWidth("100%");
			commentMmo.setWidth("100%");
			buttonPanel.adjustButtonSizes(100);
			String imgPfx = Gem.stone.getApplImageCtx();
			com.google.gwt.user.client.ui.Image formIcon = new Image(imgPfx + "upload.gif");
			setFormIcon(formIcon);
		}
	}
	
	static public class Controller extends FormController implements ClickListener, HttpPostForm.ProgressListener {
		private Map			model;
		private Dialog		view;
		private Form		explorerForm;
		
		public void setUp(Map config) {
			super.setUp(config);
			explorerForm = (Form) config.get("explorerForm");
			String folderPath = (String) config.get("folderPath");
			view = new Dialog(this);
			model = view.uploader.getInputHidden();
			int[] sz = (int[]) Gem.stone.getCargo().get("common-top.left.width.height.array");
			if (sz != null) 
				view.setPosition(sz[0], sz[1]);
			setForm(view);
			view.setCaption("Upload into " + folderPath);
			initialise(folderPath);
		}
		
		private void initialise(String path) {
			String namespace = Gem.stone.getGemPropertyAsString("requestPathInfo.namespace", null);
			model.put("namespace", namespace);
			model.put("action", "explore"); 
			model.put("path", path);
			model.put("mode", "Upload"); 
			view.okBtn.addClickListener(this);
			view.cancelBtn.addClickListener(this);
			view.uploader.setAsyncCallback(getOuterCallback());
		}
		
		public Object getModel() {
			return model;
		}

		public void onClick(Widget sender) {
			if (sender == view.okBtn) {
				prepareAndSubmitForm();
			} else {
				tearDown();
			}
		}
		
		private void prepareAndSubmitForm() {
			view.okBtn.setEnabled(false);
			String cmnt = view.commentMmo.getText();
			model.put("changeComment", cmnt);
			getFormLoadCallback().setStatus("Uploading content...");
			HttpPostRpcAsync pickup = (HttpPostRpcAsync) Gem.stone.openService(HttpPostRpc.DEFAULT_SERVICE_CTX);
			view.uploader.submit(pickup);
		}

		public void onSuccess(Object result) {
			tearDown();
			explorerForm.refresh();
			view.setProgress(0);
		}

		public void onFailure(Throwable caught) {
			Gem.stone.log("need to load the form and try again", caught);
		}

		public void onProgressReported(ProgressInfo progress) {
			if (progress != null) {
				int perc = (int) progress.phasePercentageComplete;
				view.setProgress(perc);
				String msg = "(" + perc + "%) - " + progress.statusMessage;
				view.setStatus(msg);
			}
		}
	}
}